package com.lestv.activitys;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.lestv.application.LestvApplication;
import com.lestv.entity.User;
import com.lestv.httpUtil.Cache;
import com.lestv.httpUtil.HttpRequestParams;
import com.lestv.httpUtil.HttpUtils;
import com.lestv.httpUtil.NetHandler;
import com.lestv.httpUtil.OnComplteListener;
import com.lestv.jsonBeans.BaseBean;
import com.lestv.jsonParser.BaseParser;
import com.lestv.util.SharedPrefHelper;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class RegisterActivity extends FragmentActivity implements OnClickListener, OnFocusChangeListener{
	
	//手机号输入框
	private EditText regPhonenum;
	//密码输入框
	private EditText regPassword;
	//确认密码输入框
	private EditText regPasswordAgain;
	//登录之后在手机上保存帐号和密码
	private SharedPrefHelper instance;
	//注册按钮
	private Button btnRegister;
	//返回按钮
	private ImageView btnBack;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		this.regPhonenum = (EditText)findViewById(R.id.register_phonenum);
		this.regPassword = (EditText)findViewById(R.id.register_password);
		this.regPasswordAgain = (EditText)findViewById(R.id.regiser_passwordagain);
		this.btnRegister = (Button)findViewById(R.id.bt_register);
		this.btnBack = (ImageView)findViewById(R.id.register_back);
		this.instance = SharedPrefHelper.getInstance(getApplicationContext());
		this.btnRegister.setOnClickListener(this);
		this.btnBack.setOnClickListener(this);
		this.regPhonenum.setOnFocusChangeListener(this);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
			case R.id.bt_register :
				this.register();
				break;
			case R.id.register_back :
				//跳转到登录界面
				startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
				overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
				break;
			default : break;
		}
	}
	
	/**
	 * 用户注册
	 */
	public void register() {
		String regPhonenum = this.regPhonenum.getText().toString(); 
		String regPassword = this.regPassword.getText().toString(); 
		String regPasswordAgain = this.regPasswordAgain.getText().toString();
		if(StringUtils.isNotEmpty(regPhonenum.trim())) {
			if(StringUtils.isNotEmpty(regPassword.trim()) && StringUtils.isNotEmpty(regPasswordAgain.trim())) {
				if(StringUtils.equals(regPassword.trim(), regPasswordAgain.trim())) {
					this.conectNet(regPhonenum.trim(), regPassword.trim());
				}else {
					Toast.makeText(this, "两次输入密码必须一致", Toast.LENGTH_SHORT).show();
				}
			}else {
				Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
			}
		}else {
			Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * 发送注册请求
	 * @param userName
	 * @param userPass
	 */
	private void conectNet(final String userName, final String userPass){
		HttpUtils hu = new HttpUtils();
		Map<String, String> map = new HashMap<String, String>();
		map.put("userName", userName);
		map.put("userPass", userPass);
		String entity = hu.getEntity(map);
		String path = Cache.REGISTER + "?" + entity;
		HttpRequestParams params = new HttpRequestParams(path, "utf-8",null);
		params.setMethod("GET");
		//模拟ajax异步跨域访问web服务器获取返回json信息
		hu.startConnectNet(params, new BaseParser(), new NetHandler(new OnComplteListener() {
			@Override
			public void success(BaseBean baseBean) {
				// 成功
				if ((baseBean.getEcode() == 200)) {
					Toast.makeText(RegisterActivity.this, baseBean.getErrorinfo(), Toast.LENGTH_SHORT).show();
//					String userJson = baseBean.getData().get("currentUser").toString();
//					User currentUser = JSON.parseObject(userJson, User.class);
//					Log.e("成功注册用户", currentUser.toString());
					instance.setUserName(userName);
					instance.setUserPass(userPass);
					Intent it = new Intent(RegisterActivity.this, LoginActivity.class);
					//Activity之间利用Intent传递数据，类似java的请求派发，将数据保存在Intent范围之内，只在下一个Activity有效
					//Intent传递数据支持java的8种基本数据类型、数组、集合、自定义实体类型（必须实现Serializable接口,有setter/getter方法、有无参构造方法）
					//it.putExtra("currentUser", currentUser);
					startActivity(it);
					overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
				}else {
					//失败
					Toast.makeText(RegisterActivity.this, baseBean.getErrorinfo(), Toast.LENGTH_SHORT).show();
				}
			}
			@Override// 失败
			public void fail() {
				System.out.println("失败");
			}
			@Override// 报错
			public void error(Exception e) {
				System.out.println("报错");
			}
		}));
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		//手机号码输入框失去焦点验证手机号
		if(v.getId() == R.id.register_phonenum && !hasFocus) {
			String regPhonenum = this.regPhonenum.getText().toString(); 
			Pattern p = Pattern.compile("1(3|5|7|8)\\d{9}");
			Matcher m = p.matcher(regPhonenum);
			if(m.matches()) {
				
			}else {
				Toast.makeText(RegisterActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
			}
		}
	}
}
